<!-- 商品发布 - 基础设置 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <div
      class="p-10px border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)] custom-text-small"
    >
      商品类型与销售渠道
    </div>
    <el-form-item label="商品类型" prop="spuType">
      <div>
        <div class="flex">
          <div
            class="w-130px h-65px mr-10px flex flex-col cursor-pointer justify-center flex-items-center spu-type-box"
            :class="{ 'spu-type-box-active': dict.value == formData.skus![0].skuType }"
            @click="handleSetSkuType(dict)"
            :key="dict.value"
            v-for="dict in getIntDictOptions(DICT_TYPE[`PRODUCT_SPU_TYPE${formData?.spuType}`])"
          >
            <div class="font-600"> {{ dict.label }} </div>
            <div class="font-500"> {{ dict.remark }} </div>
            <div class="virtual_san" v-if="dict.value == formData.skus![0].skuType"></div>
            <div class="virtual_dui" v-if="dict.value == formData.skus![0].skuType">✓</div>
          </div>
        </div>

        <Explaintip :msg="'商品类型在商品保存后无法修改，请谨慎选择'" />
      </div>
    </el-form-item>
    <el-form-item label="销售渠道" prop="salesChannel">
      <el-checkbox-group v-model="formData.salesChannel" @change="salesChannelChange">
        <el-checkbox
          v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SALES_CHANNEL)"
          :key="dict.value"
          :value="dict.value"
          :disabled="dict.value == 4 && formData.spuType != 1"
          >{{ dict.label }}</el-checkbox
        >
      </el-checkbox-group>
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      商品基础信息
    </div>
    <el-form-item label="商品品牌" prop="brandId" v-if="formData.spuType == 1">
      <el-select v-model="formData.brandId" class="w-120!" placeholder="请选择商品品牌">
        <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id!" />
      </el-select>
    </el-form-item>
    <el-form-item label="商品名称" prop="spuName">
      <el-input
        v-model="formData.spuName"
        :clearable="true"
        :show-word-limit="true"
        class="w-120!"
        placeholder="请输入商品名称"
      />
    </el-form-item>
    <el-form-item label="商品标题" prop="titleName" v-if="formData.salesChannel?.includes(2)">
      <el-input
        v-model="formData.titleName"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-120!"
        placeholder="请输入商品标题"
      />
    </el-form-item>
    <el-form-item label="商品副标题" prop="subTitleName" v-if="formData.salesChannel?.includes(2)">
      <el-input
        v-model="formData.subTitleName"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-120!"
        placeholder="请输入商品标题"
      />
    </el-form-item>
    <el-form-item label="商品排序" prop="sort">
      <el-input-number
        v-model="formData.sort"
        :min="0"
        placeholder="请输入商品排序"
        class="w-120!"
      />
    </el-form-item>
    <el-form-item label="商品关键字" prop="keyword" v-if="formData.salesChannel?.includes(2)">
      <el-input v-model="formData.keyword" class="w-120!" placeholder="请输入商品关键字" />
    </el-form-item>

    <el-form-item label="商品简介" prop="introduction" v-if="formData.salesChannel?.includes(2)">
      <el-input
        v-model="formData.introduction"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-120!"
        maxlength="128"
        placeholder="请输入商品简介"
        type="textarea"
      />
    </el-form-item>

    <el-form-item label="标题标签" prop="subtitle" v-if="formData.salesChannel?.includes(2)">
      <div>
        <InputWithColor
          class="w-120!"
          v-model="formData.spuTags"
          v-model:color="formData.spuColor"
          maxlength="4"
          show-word-limit
        />
        <Explaintip
          msg="显示在商品列表和商品详情标题上的标签"
          :isPicUrl="true"
          picUrl="https://v5.100cms.com.cn/static/dist/shop/img/goods_label.png"
        />
      </div>
    </el-form-item>
    <el-form-item label="商品主图" prop="picUrl">
      <div>
        <UploadImg v-model="formData.picUrl" :showDelete="!isDetail" width="80px" height="80px" />
        <Explaintip
          msg="用于商城列表、双列三列商品组、分享头图。建议尺寸：800*800像素"
          :isPicUrl="true"
          picUrl="https://v5.100cms.com.cn/static/dist/shop/img/shop_main.png"
        />
        <UploadImg
          v-model="formData.imgOblongUrl"
          :showDelete="!isDetail"
          width="170px"
          height="80px"
        />
        <Explaintip
          msg="用于装修单列商品组的商品主图，未设置时读取商品主图。建议尺寸：800*374像素"
          :isPicUrl="true"
          picUrl="https://v5.100cms.com.cn/static/dist/shop/img/single_row.png"
        />
      </div>
    </el-form-item>
    <el-form-item label="视图比例" prop="imgScale">
      <div>
        <el-radio-group v-model="formData.imgScale" class="w-120">
          <el-radio v-for="(item, index) in imgScaleProportion" :value="index" :key="index">{{
            item.p_w + ':' + item.p_h
          }}</el-radio>
        </el-radio-group>
        <Explaintip
          msg="商品详情页轮播图显示长宽比例"
          :isPicUrl="true"
          picUrl="https://vipuser3.eweishop.com/static/dist/shop/image/goods/thumb-video-ratio.png"
        />
      </div>
    </el-form-item>
    <el-form-item label="商品轮播图" prop="sliderPicUrls">
      <div>
        <UploadImgs
          v-model="formData.sliderPicUrls!"
          :showDelete="!isDetail"
          :width="`${currentImgScale.imgWidth}px`"
          :height="`${(currentImgScale.imgWidth / currentImgScale.p_w) * currentImgScale.p_h}px`"
        />
        <Explaintip
          v-if="formData.imgScale == 0"
          msg="建议尺寸: 800:800像素, 轮播图可以拖拽图片调整顺序,最多上传10张"
          :isPicUrl="true"
          picUrl="https://v5.100cms.com.cn/static/dist/shop/img/shop_swiper.png"
        />
        <Explaintip
          v-if="formData.imgScale == 1"
          msg="建议尺寸: 600*800像素, 轮播图可以拖拽图片调整顺序,最多上传10张"
          :isPicUrl="true"
          picUrl="https://v5.100cms.com.cn/static/dist/shop/img/shop_swiper.png"
        />
        <Explaintip
          v-if="formData.imgScale == 2"
          msg="建议尺寸: 800:600像素, 轮播图可以拖拽图片调整顺序,最多上传10张"
          :isPicUrl="true"
          picUrl="https://v5.100cms.com.cn/static/dist/shop/img/shop_swiper.png"
        />
        <Explaintip
          v-if="formData.imgScale == 3"
          msg="建议尺寸: 800:450像素, 轮播图可以拖拽图片调整顺序,最多上传10张"
          :isPicUrl="true"
          picUrl="https://v5.100cms.com.cn/static/dist/shop/img/shop_swiper.png"
        />
      </div>
    </el-form-item>
    <el-form-item label="添加视频" class="w-120">
      <section>
        <el-switch v-model="formData.isVideo" />
      </section>
    </el-form-item>
    <el-form-item label="视频封面" prop="videoImg" v-if="formData.isVideo">
      <div>
        <UploadImg
          v-model="formData.videoImg!"
          :showDelete="!isDetail"
          :width="`${currentImgScale.imgWidth}px`"
          :height="`${(currentImgScale.imgWidth / currentImgScale.p_w) * currentImgScale.p_h}px`"
        />
      </div>
    </el-form-item>
    <el-form-item label="视频文件" prop="videoUrl" v-if="formData.isVideo">
      <div>
        <UploadImg
          v-model="formData.videoUrl!"
          :showDelete="!isDetail"
          :width="`${currentImgScale.imgWidth}px`"
          :height="`${(currentImgScale.imgWidth / currentImgScale.p_w) * currentImgScale.p_h}px`"
        />
      </div>
    </el-form-item>
    <el-form-item label="自动播放" prop="videoAutoplay" v-if="formData.isVideo">
      <el-radio-group v-model="formData.videoAutoplay">
        <el-radio :value="false">否</el-radio>
        <el-radio :value="true">是</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="静音播放" prop="videoMuteplay" v-if="formData.isVideo">
      <el-radio-group v-model="formData.videoMuteplay">
        <el-radio :value="false">否</el-radio>
        <el-radio :value="true">是</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="商品分类" prop="categoryId" v-if="formData.salesChannel?.length > 0">
      <el-cascader
        v-model="formData.categoryId"
        :options="categoryList"
        :props="{ ...defaultProps, multiple: true }"
        class="w-120"
        clearable
        filterable
        placeholder="请选择商品分类"
      >
        <template #default="{ node, data }">
          <span>{{ data.name }}</span>
          <span v-if="!node.isLeaf">
            <template v-for="item in data.categoryBelong" :key="item">
              <dict-tag class="ml-5px" :type="DICT_TYPE.PRODUCT_SALES_CHANNEL" :value="item" />
            </template>
          </span> </template
      ></el-cascader>
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      商品销售渠道与运费
    </div>
    <el-form-item label="销售门店" v-if="formData.salesChannel?.includes(1)">
      <div class="w-100%">
        <el-radio-group v-model="formData.tenantNumType">
          <el-radio :value="1">选择门店</el-radio>
        </el-radio-group>
        <div
          v-if="formData.tenantNumType == 1"
          class="p-10px w-100% border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)]"
        >
          <StoreSelect v-model="formData.authorizedTenant" :is-details="isDetail"
            >添加销售门店
          </StoreSelect>
        </div>
      </div>
    </el-form-item>
    <el-form-item label="关联商城" v-if="formData.salesChannel?.includes(2)">
      <div class="w-100%">
        <el-radio-group :model-value="1">
          <el-radio :value="1">选择商城</el-radio>
        </el-radio-group>
        <div
          class="p-10px w-100% border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)]"
        >
          <ShopSelect v-model="formData.authorizedMallTenant" :is-details="isDetail"
            >添加销售商城
          </ShopSelect>
        </div>
      </div>
    </el-form-item>

    <el-form-item label="商品上架">
      <div>
        <el-radio-group v-model="formData.productUp">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_UP_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
        <!-- 定时上架 -->
        <div v-if="formData.productUp == 3">
          <el-date-picker
            format="YYYY-MM-DD hh:mm:ss"
            value-format="x"
            v-model="formData.productUpTime"
            :disabled-date="disabledDate"
            class="w-120!"
            type="datetime"
            placeholder="上架时间"
          />
        </div>
      </div>
    </el-form-item>
    <el-form-item label="商品下架" v-if="formData.productUp != 0">
      <div>
        <el-radio-group v-model="formData.productDown">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_DOWN_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
        <!-- 定时下架 -->
        <div v-if="formData.productDown == 1">
          <el-date-picker
            format="YYYY-MM-DD hh:mm:ss"
            value-format="timestamp"
            v-model="formData.productDownTime"
            :disabled-date="disabledDate"
            class="w-120!"
            type="datetime"
            placeholder="下架时间"
          />
        </div>
      </div>
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { defaultProps, handleTree } from '@/utils/tree'
import type { Spu } from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { CategoryVO } from '@/api/mall/product/category'

import * as ExpressTemplateApi from '@/api/mall/trade/delivery/expressTemplate'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
defineOptions({ name: 'ProductSpuInfoForm' })
const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },

  isDetail: propTypes.bool.def(false), // 是否作为详情组件
  activeName: propTypes.string.def('info')
})

const message = useMessage() // 消息弹窗

const formRef = ref() // 表单 Ref
const formData = reactive<Spu>({
  spuType: 1,
  spuId: undefined,
  salesChannel: [], //销售渠道
  brandId: undefined, // 商品品牌
  spuName: '', //商品名称
  titleName: '', // 商品标题(商城)
  subTitleName: '', //商品副标题
  sort: 0, // 商品排序 接口传参
  keyword: '', // 关键字
  introduction: '', // 商品简介
  spuTags: '', //商品标签
  spuColor: '#ff0000', //商品标签颜色
  picUrl: '', // 商品封面图
  imgOblongUrl: '', // 商品主图2, 长方形
  imgScale: 0, // 图片视频比例  1:1、3:4、4:3、16:9
  sliderPicUrls: [], // 商品轮播图
  isVideo: false, //是否有视频文件
  videoImg: '', //视频封面
  videoUrl: '', //视频链接
  videoAutoplay: false, //自动播放
  videoMuteplay: false, //禁音播放
  categoryId: undefined, // 商品分类编号
  salesOnlineChannel: [], // 线上商品销售渠道
  deliveryTypes: [], // 配送方式
  freightSet: 2, //运费设置 1固定运费 2运费模板
  freight: 0, //固定运费
  deliveryTemplateId: undefined, //运费模版id
  productUp: 0, //商品上架类型
  productUpTime: '', //商品上架时间
  productDown: 0, //商品下架类型
  productDownTime: '', // 商品下架时间
  tenantNumType: 1, //销售门店 1部分
  authorizedTenant: [], //销售门店
  tenantServiceNumType: 1, //服务门店类型 1部分
  authorizedServiceTenant: [], //服务门店

  skus: [
    {
      price: 0, //零售价
      costPrice: 0, //成本价
      cardValue: 0, // 储值卡|金额
      useDiscountType: [], //储值卡 使用折扣类型
      allDiscount: 0, //全部商品折扣
      appointSkusDiscount: {}, //储值卡 指定商品规则
      expiryDate: '', //有效期
      expiryDateUnit: 0, //有效期单位
      isDebtSales: false, //欠款销售
      isGift: false, //是否赠金
      giftValue: 0, // 赠送金额
      dedLevel: undefined, //扣款优先
      giftAccountType: undefined, //赠金到账 0一次到账 1周期到账
      appointTypeDiscount: {}, //商品类型折扣
      skuType: 1
    }
  ]
})
const rules = reactive({
  spuType: [{ required: true, message: '请选择商品类型', trigger: 'change' }],
  salesChannel: [{ required: true, message: '请选择销售渠道', trigger: 'change' }],
  spuName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  titleName: [{ required: true, message: '请输入商品标题', trigger: 'blur' }],
  videoUrl: [{ required: true, message: '请选择视频', trigger: 'blur' }]
  // categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }]
})

const handleSetSkuType = (dict) => {
  if (formData!.spuId != undefined) {
    return
  }
  formData.skus![0].skuType = dict.value
}
/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
  },
  {
    // deep: true,
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    // 如果是卡项有服务门店 其他类型商品没有服务门店
    if (formData.spuType != 2) {
      formData.authorizedServiceTenant = undefined
      formData.tenantServiceNumType = undefined
    }
    // 如果销售渠道没有选择门店 剔除对应字段
    if (!formData.salesChannel?.includes(1)) {
      formData.authorizedTenant = undefined
      formData.tenantType = undefined
    }
    await unref(formRef)?.validate()
    // 校验通过更新数据

    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【基础设置】不完善，请填写相关信息')
    emit('update:activeName', 'info')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

/** 图片比例 */
const imgScaleProportion = ref([
  {
    p_w: 1,
    p_h: 1,
    imgWidth: 80,
    videoWidth: 80
  },
  {
    p_w: 3,
    p_h: 4,
    imgWidth: 80,
    videoWidth: 80
  },
  {
    p_w: 4,
    p_h: 3,
    imgWidth: 150,
    videoWidth: 150
  },
  {
    p_w: 16,
    p_h: 9,
    imgWidth: 150,
    videoWidth: 150
  }
])
const currentImgScale = computed(() => {
  return imgScaleProportion.value[formData.imgScale!]
})
/** 初始化SpuType 信息 */
const initSpuTypeInfo = () => {
  spuTypeInfo.value = getIntDictOptions(DICT_TYPE.PRODUCT_SPU_TYPE).filter((ele) => {
    return ele.value == formData.spuType
  })[0]
}
/** 销售渠道变化 */
const salesChannelChange = () => {
  Object.assign(props.propFormData, formData)
}
/** 商品品牌 */
import * as ProductBrandApi from '@/api/mall/product/brand'
import { BrandVO } from '@/api/mall/product/brand'
/**时间范围限制 */
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now()
}
/** 商品分类 */
const categoryList = ref<CategoryVO[]>([]) // 商品分类树
const getCategoryList = async () => {
  // 获得商城分类树
  const categoryListData = await ProductCategoryApi.getCategoryList({
    categoryBelong: formData.salesChannel
  })
  categoryList.value = handleTree(categoryListData, 'id', 'parentId')
}
/** 商品品牌 */
const brandList = ref<BrandVO[]>([]) // 商品品牌列表

const getBrandList = async () => {
  // 获取商品品牌列表
  brandList.value = await ProductBrandApi.getSimpleBrandList()
}
/** 运费模板 */
const deliveryTemplateList = ref<any>([])
const getDeliveryTemplateList = async () => {
  deliveryTemplateList.value = await ExpressTemplateApi.getSimpleTemplateList()
}
/** 初始化 */

const spuTypeInfo = ref<any>({}) //商品类型 信息

onMounted(async () => {
  initSpuTypeInfo()
  // 品牌列表
  await getBrandList()
  // 运费模版
  await getDeliveryTemplateList()
  await getCategoryList()
})
</script>
<style lang="scss" scoped>
.spu-type-box {
  border: 1px solid var(--el-text-color-regular);

  position: relative;
  line-height: 24px;
  .virtual_san {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 0;
    height: 0;
    border-bottom: 26px solid var(--el-color-primary);
    border-left: 26px solid transparent;
  }
  .virtual_dui {
    position: absolute;
    bottom: -2px;
    right: 2px;
    color: #fff;
    font-family: system-ui;
  }
  &-active {
    border: 1px solid var(--el-color-primary);
  }
}
</style>
